export function getQueryInfo() {
    let r = {}, e = window.location.href.split("?");
    e[1] && e[1].split("&").forEach(a => {
        let b = a.split("=");
        r[b[0]] = b[1];
    });
    return r;
}

export function getHashInfo() {
    let hash = window.location.hash, r = {};
    if (hash) {
        hash.substring(1).split("&").forEach(a => {
            let b = a.split("=");
            r[b[0]] = b[1];
        });
    }
    return r;
}

export function setHashInfo(key, value) {
    let info = getHashInfo();
    info[key] = value;
    window.location.hash = "#" + Reflect.ownKeys(info).map(a => a + "=" + info[a]).join("&");
}

export function importScript(src) {
    return new Promise((resolve, reject) => {
        if (!document.querySelector('script[src="' + src + '"]')) {
            let script = document.createElement("script");
            script.setAttribute("src", src);
            script.addEventListener("load", () => {
                resolve();
            });
            script.addEventListener("error", () => {
                reject();
            });
            document.head.appendChild(script);
        } else {
            resolve();
        }
    });
}

export function getFirstDate(year, month) {
    return `${year}/${month < 10 ? ('0' + month) : month}/01 00:00:00`;
}

export function getLastDate(year, month) {
    let d = new Date(year, month, 0), _month = d.getMonth() + 1, day = d.getDate();
    return `${d.getFullYear()}/${_month < 10 ? '0' + _month : _month}/${day < 10 ? '0' + day : day} 23:59:59`;
}

export function format(date, format) {
    if (arguments.length === 1) {
        format = date;
        date = new Date();
    }
    let map = {
        y: date.getFullYear(),
        M: (date.getMonth() + 1),
        d: date.getDate(),
        h: date.getHours(),
        m: date.getMinutes(),
        s: date.getSeconds()
    };
    return Reflect.ownKeys(map).reduce((a, b) => {
        return a.replace(new RegExp(`[${b}]+`, "g"), (str) => {
            let value = map[b] + "";
            if (str.length !== value.length) {
                return str.length > value.length ? (Array.apply(null, Array(str.length - value.length)).map(() => "0").join("") + value) : value.substring(str.length);
            } else {
                return value;
            }
        });
    }, format);
}